//模型，负责跟数据库打交道
package models

import (
	"math"
	"strings"
	"time"

	"github.com/spf13/viper"
	"gopkg.in/mgo.v2"
)

// 创建MongoDB会话
func NewMongodbSession(clusterName string) (session *mgo.Session, err error) {
	config := viper.GetStringMap("mongodb." + clusterName)
	info := mgo.DialInfo{
		Addrs: strings.Split(config["addrs"].(string), ","),
	}
	timeout, ok := config["timeout"].(int64)
	if ok {
		info.Timeout = time.Duration(timeout * int64(math.Pow10(9)))
	}
	session, err = mgo.DialWithInfo(&info)
	if err != nil {
		return nil, err
	}
	session.SetMode(mgo.Monotonic, false)
	session.SetSafe(&mgo.Safe{
		WMode: "majority",
	})
	return session, nil
}

// 创建MongoDB数据库访问对象
func NewMongodbDB(clusterName string, dbName string) (db *mgo.Database, err error) {
	session, err := NewMongodbSession(clusterName)
	if err != nil {
		return nil, err
	}
	return session.DB(dbName), nil
}

// 创建MongoDB表访问对象
func NewMongodbColl(clusterName string, dbName string, collName string) (coll *mgo.Collection, err error) {
	db, err := NewMongodbDB(clusterName, dbName)
	if err != nil {
		return nil, err
	}
	return db.C(collName), nil
}

// ...
